import configInfo from '../base/profile/config.json';
import { Toast, Indicator } from 'mint-ui';
require('./appservice.js');
(!/cross-bm/i.test(navigator.userAgent))&&require('./analogApp.js');
const JsBridgeFactory = {
    buildJsBridge: function () {
        if (this.bridgeInstance) {
            return this.bridgeInstance;
        }else if ((/cross-bm/i.test(navigator.userAgent) || isZHKIOS)) {
            this.bridgeInstance = new ZHKJSBridgeAdapter();
        }
        else {
            this.bridgeInstance = new DefaultJSBridgeAdapter();
        }
        this.bridgeInstance = new ZHKJSBridgeAdapter()
        return this.bridgeInstance;
    }
};

class JsBridge {
  constructor(props) {
      this.containerIsReady = false; // TODO 上线需要修改为false
      this.delay = 0;
      this.backEventListners = {};
      this.resumeEventListners = {};
      this.newOrderEventListners = {};
      this.deviceInfo = {
          isZHK: (/cross-bm/i.test(navigator.userAgent) || isZHKIOS),
          isAndroid: /android/i.test(navigator.userAgent),
          isIOS: /iphone/i.test(navigator.userAgent)
      };
  }

  preInvoke() {
      if (!this.containerIsReady) {
          this.delay = 100;
      }
      else {
          this.delay = 0;
      }
  }
  updateNativePage(param,callback){
      this.preInvoke();
      this.doUpdateNativePage(param,callback);
  }
  doUpdateNativePage(param,callback){
  }
  hideSplash(){
      this.preInvoke();
      this.doHideSplash();
  }
  doHideSplash(){
  }
  tradePay(params, callback) {
      this.preInvoke();
      this.doTradePay(params, callback);
  }
  doTradePay(params,callback) {
  }
  upgradeApp(params, callback) {
      this.preInvoke();
      this.doUpgradeApp(params, callback);
  }
  doUpgradeApp(params,callback) {
  }
  getCurrentAppVersion(callback) {
      this.preInvoke();
      this.doGetCurrentAppVersion(callback);
  }
  doGetCurrentAppVersion(callback) {
  }
  gotoWallet(params) {
      this.preInvoke();
      this.doGotoWallet(params);
  }
  doGotoWallet(params) {
  }
  selectPicture(params, succCallback, failCallback) {
      this.preInvoke();
      this.doSelectPicture(params, succCallback, failCallback);
  }
  doSelectPicture(params, succCallback, failCallback) {
  }
  uploadPic(params, succCallback, failCallback) {
      this.preInvoke();
      this.doUploadPic(params, succCallback, failCallback);
  }
  doUploadPic(params, succCallback, failCallback) {
  }
  testVoiceBroadcast(params) {
      this.preInvoke();
      this.doTestVoiceBroadcast(params);
  }
  doTestVoiceBroadcast(params) {
  }
  scanQRCode(params, callback) {
      this.preInvoke();
      this.doScanQRCode(params, callback);
  }
  doScanQRCode(params, callback) {
  }
  getNearByWIFI(callback) {
      this.preInvoke();
      this.doGetNearByWIFI(callback);
  }
  doGetNearByWIFI(callback) {
  }
  startBroadcast(params,callback) {
      this.preInvoke();
      this.doStartBroadcast(params,callback);
  }
  doStartBroadcast(params,callback){
  }
  stopBroadcast(callback) {
      this.preInvoke();
      this.doStopBroadcast(callback);
  }
  doStopBroadcast(callback){
  }
  savePicture(params, callback) {
      this.preInvoke();
      this.doSavePicture(params, callback);
  }
  doSavePicture(params, callback) {
  }
  viewPicture(params, callback) {
      this.preInvoke();
      this.doViewPicture(params, callback);
  }
  doViewPicture(params, callback) {
  }
  shardBySystem(params) {
      this.preInvoke();
      this.doShardBySystem(params);
  }
  doShardBySystem(params) {
  }
  setTitle(titleStr,showClose) {
      this.preInvoke();
      this.doSetTitle(titleStr,showClose);
  }
  doSetTitle(titleStr,showClose) {
      // implemented by subclass
  }
  openWifi() {
      this.preInvoke();
      this.doOpenWifi();
  }
  doOpenWifi() {
  }
  setRightOptionButton(params, callback) {
      this.preInvoke();
      this.doSetRightOptionButton(params, callback);
  }
  doSetRightOptionButton(params, callback) {
      // implemented by subclass
  }
  hideOptionMenu() {
      this.preInvoke();
      this.doHideOptionMenu();
  }
  doHideOptionMenu() {
      // implemented by subclass
  }
    // private method
  parseParseId() {
      let href = window.location.href;
      let startIndex = href.indexOf('#');
      let endIndex = href.indexOf('?');
      let pageId = '';
      if (endIndex == -1) {
          pageId = href.substring(startIndex + 1);
      }
      else {
          pageId = href.substring(startIndex + 1, endIndex);
      }

      return pageId;
  }

  getCustomBackEvent() {
      let pageId = this.parseParseId();
      let customBackEvent = null;
      for (var backKey in jsBridge.backEventListners) {
          if (pageId == backKey) {
              customBackEvent = jsBridge.backEventListners[backKey];
          }

      }

      return customBackEvent;
  }

  getCustomResumeEvent() {
      let pageId = this.parseParseId();
      let customResumeEvent = null;
      for (var resumeKey in jsBridge.resumeEventListners) {
          if (pageId == resumeKey) {
              customResumeEvent = jsBridge.resumeEventListners[resumeKey];
          }

      }

      return customResumeEvent;
  }
  getCustomNewOrderEvent() {
      let pageId = this.parseParseId();
      let customNewOrderEvent = null;
      for (var newOrderKey in jsBridge.newOrderEventListners) {
          if (pageId == newOrderKey) {
              customNewOrderEvent = jsBridge.newOrderEventListners[newOrderKey];
          }

      }

      return customNewOrderEvent;
  }


  // implemented by subclass

  /*
  执行返回事件，机制如下：
  1 如果返回事件为空，执行浏览器的默认行为（ios的钉钉会执行goBack方法）
  2 如果返回事件不为空，且执行结果为true，那接着执行浏览器的默认行为（ios的钉钉会执行goBack方法），return true给事件处理
  3 如果返回事件不为空,且执行结果为false，那不接着执行浏览器的默认行为，直接return false给浏览器事件处理
  */

  executeBackEvent(e) {
      // let customBackEvent = this.getCustomBackEvent();
      // if (customBackEvent) {
      // 	e && e.preventDefault();
      // 	customBackEvent();
      // 	return false;
      // }else{
      // 	return true;
      // }
  }

  executeResumeEvent(e) {
      // 忽略容器默认行为
      e && e.preventDefault();

      let customResumeEvent = this.getCustomResumeEvent();
      if (customResumeEvent) {
          customResumeEvent();
          return false;
      }
      else {
          // 如果授权没有完成就刷新当前页
          // if (h5ServiceUtils.getAuthStatus() != Constants.AUTH_STATUS.ED) {
          //     // 默认实现：刷新当前页
          //     window.location.reload();
          //     return false;
          // }
      }
  }

  // canGoBack(){
  // 	return history.length>1;
  // }
  executeNewOrderEvent(e) {
      // let customBackEvent = this.getCustomBackEvent();
      // if (customBackEvent) {
      // 	e && e.preventDefault();
      // 	customBackEvent();
      // 	return false;
      // }else{
      // 	return true;
      // }
  }
  addBackEventListener(callback) {
      this.preInvoke();
      this.doAddBackEventListener(callback);
  }
  doAddBackEventListener(callback) {
      // implemented by subclass
      let pageId = this.parseParseId();
      // let exists = false;
      // for (var backKey in this.backEventListners) {
      // 	if (pageId == backKey) {
      // 		exists = true;
      // 	}
      // }

      // if (!exists) {
      // 	this.backEventListners[pageId] = callback;
      // }

      this.backEventListners[pageId] = callback;
  }

  addResumeEventListener(callback) {
      this.preInvoke();
      this.doAddResumeEventListener(callback);
  }
  doAddResumeEventListener(callback) {
      let pageId = this.parseParseId();
      this.resumeEventListners[pageId] = callback;
  }
  addNewOrderEventListener(callback) {
      this.preInvoke();
      this.doAddNewOrderEventListener(callback);
  }
  doAddNewOrderEventListener(callback) {
      let pageId = this.parseParseId();
      this.newOrderEventListners[pageId] = callback;
  }
  removeBackEventListener(callback) {
      this.preInvoke();
      this.doRemoveBackEventListener(callback);
  }
  doRemoveBackEventListener() {
      let pageId = this.parseParseId();
      for (var backKey in this.backEventListners) {
          if (pageId == backKey) {
              delete this.backEventListners[backKey];
              break;
          }

      }
  }

  removeResumeEventListener(callback) {
      this.preInvoke();
      this.doRemoveResumeEventListener(callback);
  }
  doRemoveResumeEventListener() {
      let pageId = this.parseParseId();
      for (var resumeKey in this.resumeEventListners) {
          if (pageId == resumeKey) {
              delete this.resumeEventListners[resumeKey];
              break;
          }

      }
  }
  removeNewOrderEventListener(callback) {
      this.preInvoke();
      this.doRemoveNewOrderEventListener(callback);
  }
  doRemoveNewOrderEventListener() {
      let pageId = this.parseParseId();
      for (var newOrderKey in this.newOrderEventListners) {
          if (pageId == newOrderKey) {
              delete this.newOrderEventListners[newOrderKey];
              break;
          }

      }
  }
openWindow(params) {
      this.preInvoke();
      this.doOpenWindow(params);
  }

  // 关闭窗口
  closeWindow() {
      this.preInvoke();
      this.doCloseWindow();
  }

  // Toast
  // {
  //	"content" : "" //内容
  //	"type" : "success/error"	//图标类型，默认info
  //	"success" : function(){}	//可选，回调函数
  // }
  showToast(params) {
      this.preInvoke();
      this.doShowToast(params);
  }

  // 显示loading
  showLoading(content) {
      this.preInvoke();
      this.doShowLoading(content);
  }

  // 关闭loading
  closeLoading() {
      this.preInvoke();
      this.doCloseLoading();
  }

  /**
{
   title:"",//副标题
   message:"",//框文本
   button:"",//按钮文字
   onPress:function(){//点击按钮以后回调

   }
}
*/
  alert(params) {
      this.preInvoke();
      this.doAlert(params);
  }

  /**
 * 确认框
 * @param  {[type]} params
 * {
 * 		title : "标题",
 * 		content : "正文",
 * 		okText : "确定文本",
 * 		cancelText : "取消文本",
 * 		okCallback : 确定回调
 * }
 * @return {[type]}        [description]
 */
  confirm(params) {
      this.preInvoke();
      this.doConfirm(params);
  }

  goBack(success, fail) {
      this.preInvoke();
      this.doGoBack(success, fail);
  }

  callUp(params) {
      this.preInvoke();
      this.doCallUp(params);
  }
  doCallUp(params) {

  }
  goNativePage(params) {
    this.preInvoke();
    this.doGoNativePage(params);
  }

  routerBeforeEach(params){
    this.preInvoke();
    this.doRouterBeforeEach(params);
  }
}

/*纵横掌柜app*/
class ZHKJSBridgeAdapter extends JsBridge {
  constructor(props) {
      super(props);
  }
  doRouterBeforeEach(params) {
    AppUtil.call(AppUtil.APIS.ROUTER_BEFORE_EACH, params);
  }
  doGoNativePage(params) {
    AppUtil.call(AppUtil.APIS.OPEN_NATIVEPAGE, params);
  }
  doHideSplash(){
      AppUtil.call2(AppUtil.APIS.HIDE_SPLASH);
  }
  doUpdateNativePage(param,callback){
      AppUtil.call2(AppUtil.APIS.UPDATE_NATIVE_PAGE,param,function (result) {
          callback&&callback(result);
      });
  }
  doTradePay(param,callback) {
      AppUtil.call(AppUtil.APIS.TRADE_PAY,param,function (result) {
          callback&&callback(result);
      });
  }
  doUpgradeApp(param,callback) {
      AppUtil.call(AppUtil.APIS.UPGRADE_APP,param,function (result) {
          callback&&callback(result);
      });
  }
  doGetCurrentAppVersion(callback) {
      AppUtil.call(AppUtil.APIS.GET_APP_VERSION,{},function (result) {
          callback&&callback(result);
      });
  }
  doGotoWallet(params) {
      AppUtil.call(AppUtil.APIS.GOTO_WALLET, params);
  }
  doTestVoiceBroadcast(params) {
      AppUtil.call(AppUtil.APIS.TEST_VOICE_BROADCAST, { 'text': params.text || '支付宝收款100元' });
  }
  doScanQRCode(params, callback) {
      AppUtil.call(AppUtil.APIS.SCAN, {
          type: params.type,
          title:params.title||'扫一扫',
          text:params.text||'请将取景器对准条形码/二维码'
      }, function (result) {
          callback && callback(result);
      });
  }
  doGetNearByWIFI(callback) {
      AppUtil.call(AppUtil.APIS.GET_NEARBY_WIFI, {}, function (result) {
          callback && callback(result);
      });
  }
  doStartBroadcast(params,callback) {
      AppUtil.call(
          AppUtil.APIS.START_BROADCAST,
          {
            type: "setUpNetwork",
            content: params.content
          },
          function(result) {
              callback && callback(result);
          }
        );
  }
  doStopBroadcast(callback) {
      AppUtil.call(
          AppUtil.APIS.STOP_BROADCAST,{},function(result) {
              callback && callback(result);
          }
      );
  }

  doSavePicture(params, callback) {
      AppUtil.call(AppUtil.APIS.SAVE_PICTURE, {
          url: params.url
      }, function (result) {
          callback && callback(result);
      });
  }
  doViewPicture(params, callback) {
      AppUtil.call(AppUtil.APIS.VIEW_PICTURE, {
          files: params.files,
          current: params.current || 0,
      }, function (result) {
          callback && callback(result);
      });
  }
  doShardBySystem(params) {
      AppUtil.call(AppUtil.APIS.SHARD_BY_SYSTEM, params);
  }
  doSetTitle(titleStr,showClose) {
      AppUtil.call(AppUtil.APIS.SET_TITLE, {
          title: titleStr,
          color: '#333333',
          background: '#ffffff',
          showClose:showClose?true:false
      });
  }
  doOpenWifi() {
      AppUtil.call(AppUtil.APIS.OPEN_WIFI);
  }
  doSetRightOptionButton(params, callback) {
      // 设置右按钮属性
      AppUtil.call(AppUtil.APIS.SET_OPTION_MENU, {
          title: params.title, // 与icon二选一
          icon: params.icon,
          redDot: params.redDot,
          color: params.color ? params.color : '#333333', // 必须以＃开始ARGB颜色值
      });
      AppUtil.call(AppUtil.APIS.SHOW_OPTION_MENU);
      $(document)
          .off('optionMenu')
          .on('optionMenu', function (e) {
              callback && callback();
          });
  }
  doHideOptionMenu() {
      AppUtil.call(AppUtil.APIS.HIDE_OPTION_MENU);
  }

  doOpenWindow(params) {
      let title;
      if (params.needTitle) {
          title = {
              title: params.title?params.title:" ",
              color: '#333333',
              background: '#ffffff'
          };
      } else {
          title = null;
      }
      AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
          url: params.url,
          target: params.target || 'server',
          suffixParams: params.suffixParams || '',
          param: {
              title: title
          }
      });
  }

  doCloseWindow() {
      AppUtil.call(AppUtil.APIS.POP_WINDOW);
  }
  doShowToast(params) {
      switch (params.type) {
          case 'error':
              Toast({
                  message: params.content,
                  duration: 3000
              });
              break;
          case 'success':
              Toast({
                  message: params.content,
                  iconClass: 'icon icon-success',
                  duration: 3000
              });
              break;
          default:
              Toast({
                  message: params.content,
                  duration: 3000
              });
              break;
      }
      setTimeout(() => {
          params.success || function () { };
      }, 3000);
  }
  doShowLoading(params) {
      Indicator.open('加载中...');
      params.onSuccess && params.onSuccess();
  }

  doCloseLoading() {
      Indicator.close();
  }

  doConfirm(params) {
      AntConfirm(params.title, params.content, [{ text: params.cancelText, onPress: () => params.cancelCallback && params.cancelCallback() }, { text: params.okText, onPress: () => params.okCallback && params.okCallback() }]);
  }

  doSelectPicture(params, succCallback, failCallback) {
      let selectedOption;
      if (params.options == '拍照') {
          selectedOption = AppUtil.APIS.TAKE_PICTURE;
      } else {
          selectedOption = AppUtil.APIS.SELECT_PICTURE;
      }
      let data={
          compress: params.compress || { sizeLimit: '2', unit: 'M' },
          crop:params.crop || { heightRatio: 600, widthRatio: 600 },
          format: 'JPG',
          maxNum: 1
      };

      if(params['noCrop']){
          data={
              compress: params.compress || { sizeLimit: '2', unit: 'M' },
              format: 'JPG',
              maxNum: 1
          };
      }
      if(params.maxSize){
          data['maxSize']=params.maxSize;
      }else if(!params.crop){
          data['maxSize']={width:'2000',height:'2000'};
      }
      AppUtil.call(selectedOption,
          data, function (result) {
              if (result.code == 0) {
                  if (selectedOption == AppUtil.APIS.SELECT_PICTURE) {
                      result.resultObject = result.resultObject[0];
                  }
                  succCallback && succCallback(result);
              }
              else if (result.code == -1) {
                  failCallback && failCallback(result);
              }
          });

  }

  doUploadPic(params,succCallback,failCallback) {
      let self = this;
      Indicator.open('加载中...');
      AppUtil.call(AppUtil.APIS.UPLOAD_PICTURE, { url: params.url, file: params.file, data: params.data }, function (result) {
          if (result.success.toString() !== 'true') {
              Indicator.close();
              result = { code: '-99', data: params.data, msg: '网络连接失败,请检查您的网络!' };
              failCallback && failCallback(result);
          }
          else {
              Indicator.close();
              if (result.code == '0') {
                  succCallback(result.resultObject);
              }
              else {
                  failCallback && failCallback(result);
              }
          }
      });
  }

  doGoBack(success, fail) {
      AppUtil.call(AppUtil.APIS.POP_WINDOW);
  }

  executeBackEvent(e) {
      let customBackEvent = this.getCustomBackEvent();
      if (customBackEvent) {
          let executeResult = customBackEvent();
          if (executeResult) {
              // 自己有处理逻辑，但是最终还是希望让浏览器继续处理
              return true;
          }
          else {
              // 自己有处理逻辑并且不希望浏览器继续处理
              e && e.preventDefault();
              return false;
          }
      }
      else {
          return true; // 继续让浏览器处理默认行为
      }
  }
  executeNewOrderEvent(e) {
      let customNewOrderEvent = this.getCustomNewOrderEvent();
      if (customNewOrderEvent) {
          customNewOrderEvent();
      }
  }
  doCallUp(params) {
      AppUtil.call(AppUtil.APIS.DIAL, { "mobile": params.tel }, function (result) {
          if (result == -1 || result == '-1') {
              params.failCallback && params.failCallback();
          } else {
              params.succCallback && params.succCallback();
          }
      });
  }
}
class DefaultJSBridgeAdapter extends JsBridge {
    constructor(props) {
        super(props);
        this.containerIsReady = true;
    }
    doShardBySystem() {

    }
    doSetTitle(titleStr) {
        document.title = titleStr;
    }
    doOpenWifi() {
    }
    doSetRightOptionButton(params, callback) {
        $(document)
            .off('setOptionMenu')
            .on('setOptionMenu', function () {
                callback && callback();
            });
    }
    doHideOptionMenu() { }

    doOpenWindow(params) { alert(111)
        window.location.href = params.url;
    }

    doCloseWindow() {
        history.back();
    }

    doShowToast(params) {
        alert(params.content);
    }

    doShowLoading(params) {
        params.onSuccess && params.onSuccess();
    }

    doConfirm(params) {
        let result = confirm(params.content);
        if (result) {
            params.okCallback && params.okCallback();
        }
    }

    doCloseLoading() { }

    doGoBack(success, fail) {
        history.back();
    }

    executeBackEvent(e) {
        let customBackEvent = this.getCustomBackEvent();
        if (customBackEvent) {
            let executeResult = customBackEvent();
            if (executeResult) {
                // 自己有处理逻辑，但是最终还是希望让浏览器继续处理
                return true;
            }
            else {
                // 自己有处理逻辑并且不希望浏览器继续处理
                e && e.preventDefault();
                return false;
            }
        }
        else {
            !e && this.goBack(); // ios 里面没有e，需要调用goBack事件
            return true; // 继续让浏览器处理默认行为
        }
    }
}

let jsBridge = JsBridgeFactory.buildJsBridge();

/*================ready event====================*/

if (jsBridge.deviceInfo.isZHK) {
    $(document)
        .off('back')
        .on('back', function (e) {
            return jsBridge.executeBackEvent(e);
        });

    // 监听resume事件
    $(document)
        .off('resume')
        .on('resume', function (e) {
            return jsBridge.executeResumeEvent(e);
        });
    // 监听事件
    $(document)
        .off('newOrder')
        .on('newOrder', function (e) {
            return jsBridge.executeNewOrderEvent(e);
        });
}
!jsBridge.deviceInfo.isAlipay &&
    !jsBridge.deviceInfo.isDing && !jsBridge.deviceInfo.isZHK &&
    $(document)
        .off('back')
        .on('back', function (e) {
            let executeResult = jsBridge.executeBackEvent(e);

            if (executeResult) {
                if (e.defaultPrevented) {//默认行为被忽略了
                    return executeResult;
                } else {//默认行为没有被忽略，执行默认行为
                    history.back();
                }
            }

            return executeResult;
        });
export default jsBridge;
